﻿// © HighVoltz
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Media;
using Styx.Common;
using PetFighterBot;

namespace HighVoltz
{
    public static class Updater
    {
        private const string PbSvnUrl = "http://petfighter.googlecode.com/svn/trunk/source/PetFighter/";
        private const string PbChangeLogUrl = "http://code.google.com/p/PetFighter/source/detail?r=";

        private static readonly Regex _linkPattern = new Regex(@"<li><a href="".+"">(?<ln>.+(?:..))</a></li>",
                                                               RegexOptions.CultureInvariant);

        private static readonly Regex _changelogPattern =
            new Regex(
                "<h4 style=\"margin-top:0\">Log message</h4>\r?\n?<pre class=\"wrap\" style=\"margin-left:1em\">(?<log>.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?)</pre>",
                RegexOptions.CultureInvariant);

        public static void CheckForUpdate()
        {
            try
            {
                //Professionbuddy.Log("Checking for new version");
                int remoteRev = GetRevision();
                //if (GlobalPBSettings.Instance.CurrentRevision != remoteRev &&
                //    Professionbuddy.Svn.Revision < remoteRev)
                //{
                    PetFighter.slog(Colors.GreenYellow, "Updater - © HighVoltz");
                    PetFighter.slog(Colors.GreenYellow, "Downloading Update ..");
                    DownloadFilesFromSvn(new WebClient(), PbSvnUrl);
                    PetFighter.slog(Colors.GreenYellow, "Download complete.");
                    //GlobalPBSettings.Instance.CurrentRevision = remoteRev;
                    //GlobalPBSettings.Instance.Save();
                    PetFighter.slog(Colors.Red, "A new version of PetFighter was installed. Please restart Honorbuddy");
                    if (GetChangeLog(remoteRev).Length > 0)
                    {
                        Logging.Write(Colors.DodgerBlue, "************* Change Log ****************");
                        Logging.Write(Colors.SkyBlue, GetChangeLog(remoteRev));
                        Logging.Write(Colors.DodgerBlue, "*****************************************");
                        System.Windows.Forms.MessageBox.Show("A new version of PetFighter was installed.\n - Please restart Honorbuddy! \n\nChangeLog:\n" + GetChangeLog(remoteRev), "PetFighter - Updater", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    }
                //}
                //else
                //{
                //    Professionbuddy.Log("No updates found");
                //}
            }
            catch (Exception ex)
            {
                Logging.WriteException(Colors.Firebrick, ex);
            }
        }

        private static int GetRevision()
        {
            var client = new WebClient();
            string html = client.DownloadString(PbSvnUrl);
            var pattern = new Regex(@" - Revision (?<rev>\d+):", RegexOptions.CultureInvariant);
            Match match = pattern.Match(html);
            if (match.Success && match.Groups["rev"].Success)
                return int.Parse(match.Groups["rev"].Value);
            throw new Exception("Unable to retreive revision");
        }

        private static void DownloadFilesFromSvn(WebClient client, string url)
        {
            string html = client.DownloadString(url);
            MatchCollection results = _linkPattern.Matches(html);

            IEnumerable<Match> matches = from match in results.OfType<Match>()
                                         where match.Success && match.Groups["ln"].Success
                                         select match;
            foreach (Match match in matches)
            {
                string file = RemoveXmlEscapes(match.Groups["ln"].Value);
                string newUrl = url + file;
                if (newUrl[newUrl.Length - 1] == '/') // it's a directory...
                {
                    DownloadFilesFromSvn(client, newUrl);
                }
                else // its a file.
                {
                    string filePath, dirPath;
                    if (url.Length > PbSvnUrl.Length)
                    {
                        string relativePath = url.Substring(PbSvnUrl.Length);
                        dirPath = Path.Combine(GetProfessionbuddyPath(), relativePath);
                        filePath = Path.Combine(dirPath, file);
                    }
                    else
                    {
                        dirPath = Environment.CurrentDirectory;
                        filePath = Path.Combine(GetProfessionbuddyPath(), file);
                    }
                    PetFighter.dlog("Downloading {0}", file);
                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);
                    client.DownloadFile(newUrl, filePath);
                }
            }
        }

        private static string RemoveXmlEscapes(string xml)
        {
            return
                xml.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace(
                    "&apos;", "'");
        }

        private static string GetChangeLog(int revision)
        {
            var client = new WebClient();
            string html = client.DownloadString(PbChangeLogUrl + revision);
            Match match = _changelogPattern.Match(html);
            if (match.Success && match.Groups["log"].Success)
                return RemoveXmlEscapes(match.Groups["log"].Value);
            return null;
        }

        private static string GetProfessionbuddyPath()
        {   // taken from Singular.
            // bit of a hack, but location of source code for assembly is only.
            var asmName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            var len = asmName.LastIndexOf("_", StringComparison.Ordinal);
            var folderName = asmName.Substring(0, len);

            var botsPath = Styx.Helpers.GlobalSettings.Instance.BotsPath;
            if (!Path.IsPathRooted(botsPath))
            {
                botsPath = Path.Combine(Utilities.AssemblyDirectory, botsPath);
            }
            return Path.Combine(botsPath, folderName);
        }
    }
}